package com.example.dangerouscargodriver.ui.activity;

import androidx.core.content.FileProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.bjpopupwindow.view.BottomDialog;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.wheelpicker.WheelPickerView;
import com.baiju.style.wheelpicker.bean.WheelItemBean;
import com.baiju.style.wheelpicker.config.WheelPickerConfig;
import com.baiju.style.wheelpicker.listener.OnWheelItemClickListener;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.ImageUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class EnterPlatformCompanyStepOneActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "EnterPlatform";
    private static final int ACTION_BUSINESS_IDENTIFY_OFFSET = 0;
    private static final int ACTION_BUSINESS_LICENSE_OFFSET = 1;
    private static final int ACTION_COMPANY_IDENTIFY_OFFSET = 2;
    private static final int ACTION_CHEMICALS_IDENTIFY_OFFSET = 3;

    //相册请求码
    private static final int ALBUM_REQUEST_CODE = 1;
    //相机请求码
    private static final int CAMERA_REQUEST_CODE = 2;

    private static final int SELECT_BUSINESS_IDENTIFY = 0;
    private static final int SELECT_BUSINESS_LICENSE = 1;
    private static final int SELECT_COMPANY_IDENTIFY = 2;
    private static final int SELECT_CHEMICALS_IDENTIFY = 3;

    private ActionBar mActionBar = null;
    private Button mCommit = null;

    private LinearLayout mBusinessIdentifyLayout = null;
    private ImageView mBusinessIdentifyIv = null;
    private ImageView mBusinessIdentifyIvLoading = null;
    private boolean mBusinessIdentifyIvLoaded = false;

    private LinearLayout mBusinessLicenseLayout = null;
    private ImageView mBusinessLicenseIv = null;
    private ImageView mBusinessLicenseIvLoading = null;
    private boolean mBusinessLicenseIvLoaded = false;

    private LinearLayout mCompanyIdentifyLayout = null;
    private ImageView mCompanyIdentifyIv = null;
    private ImageView mCompanyIdentifyIvLoading = null;
    private boolean mCompanyIdentifyIvLoaded = false;

    private LinearLayout mChemicalsIdentifyLayout = null;
    private ImageView mChemicalsIdentifyIv = null;
    private ImageView mChemicalsIdentifyIvLoading = null;
    private boolean mChemicalsIdentifyIvLoaded = false;
    private LinearLayout mChemicalsIdentifyManagerLayout = null;

    private LinearLayout mCompanyTypeSelector = null;
    private ArrayList<WheelItemBean> mCompanyTypeArray;
    private WheelPickerView mCompanyTypePickerView = null;
    private WheelItemBean mCompanyTypeSelectedBean = null;
    private TextView mCompanyTypeTv = null;

    private BottomDialog mBottomDialog = null;

    //调用照相机返回图片文件
    private File mTempFile;

    private HashMap<String, String> mSelectPicture = null;
    private int mSelectType = SELECT_BUSINESS_IDENTIFY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(EnterPlatformCompanyStepOneActivity.class);
        setContentView(R.layout.activity_enter_platform_company_step_one);
        AppManager.getAppManager().addActivity(this);

        mSelectPicture = new HashMap<>();
        mBottomDialog = new BottomDialog();
        mBottomDialog.setOnItemClickListener(new BottomDialog.OnItemClickListener() {
            @Override
            public void onCamera() {
                getPicFromCamera();
            }

            @Override
            public void onAlbum() {
                getPicFromAlbum();
            }

            @Override
            public void onCancel() {

            }
        });

        mCommit = findViewById(R.id.btn_add_bill);
        mCommit.setOnClickListener(this);

        mBusinessIdentifyLayout = findViewById(R.id.layout_business_identify);
        mBusinessIdentifyIv = findViewById(R.id.iv_business_identify);
        mBusinessIdentifyIvLoading = findViewById(R.id.iv_business_identify_loading);
        mBusinessIdentifyLayout.setOnClickListener(this);

        mBusinessLicenseLayout = findViewById(R.id.layout_business_license);
        mBusinessLicenseIv = findViewById(R.id.iv_business_license);
        mBusinessLicenseIvLoading = findViewById(R.id.iv_business_license_loading);
        mBusinessLicenseLayout.setOnClickListener(this);

        mCompanyIdentifyLayout = findViewById(R.id.layout_company_identify);
        mCompanyIdentifyIv = findViewById(R.id.iv_company_identify);
        mCompanyIdentifyIvLoading = findViewById(R.id.iv_company_identify_loading);
        mCompanyIdentifyLayout.setOnClickListener(this);

        mChemicalsIdentifyLayout = findViewById(R.id.layout_chemicals_identify);
        mChemicalsIdentifyIv = findViewById(R.id.iv_chemicals_identify);
        mChemicalsIdentifyIvLoading = findViewById(R.id.iv_chemicals_identify_loading);
        mChemicalsIdentifyLayout.setOnClickListener(this);
        mChemicalsIdentifyManagerLayout = findViewById(R.id.layout_chemicals_identify_manager);

        initCompanyTypeArray();
        mChemicalsIdentifyManagerLayout.setVisibility(View.GONE);
        mCompanyTypeSelector = findViewById(R.id.layout_company_type);
        mCompanyTypeSelector.setOnClickListener(this);
        mCompanyTypePickerView = new WheelPickerView();
        mCompanyTypePickerView.init(this, mCompanyTypeArray);
        mCompanyTypeTv = findViewById(R.id.tv_company_type);
        mCompanyTypeTv.setText(mCompanyTypeSelectedBean.getName());

        mActionBar = findViewById(R.id.actionEnterPlatformCompanyStepOne);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private boolean checkUploadStatus(){
        if(mCompanyTypeSelectedBean.getId().equals("69")) {
            return mBusinessLicenseIvLoaded && mBusinessIdentifyIvLoaded && mCompanyIdentifyIvLoaded &&
                    mChemicalsIdentifyIvLoaded;
        }
        else{
            return mBusinessLicenseIvLoaded && mBusinessIdentifyIvLoaded && mCompanyIdentifyIvLoaded;
        }
    }

    private void initCompanyTypeArray(){
        mCompanyTypeArray = new ArrayList<>();
        WheelItemBean bean = new WheelItemBean();
        bean.setName("危险品运输公司");
        bean.setId("26");
        mCompanyTypeArray.add(bean);
        WheelItemBean bean2 = new WheelItemBean();
        bean2.setName("危险品储运公司");
        bean2.setId("69");
        mCompanyTypeArray.add(bean2);

        mCompanyTypeSelectedBean = bean;
    }

    private void addCompanyType(WheelItemBean type) {
        mCompanyTypeTv.setText(type.getName());
        if(type.getId().equals("26")){
            mChemicalsIdentifyManagerLayout.setVisibility(View.GONE);
        }
        else{
            mChemicalsIdentifyManagerLayout.setVisibility(View.VISIBLE);
        }
    }

    private void showCompanyTypeSelector(){
        WheelPickerConfig pickerConfig = new WheelPickerConfig.Builder()
                .title("选择类型")
                .visibleItemsCount(4)
                .defaultItem(mCompanyTypeSelectedBean.getName())
                .itemCyclic(false)
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mCompanyTypePickerView.setConfig(pickerConfig);
        mCompanyTypePickerView.setOnItemClickListener(new OnWheelItemClickListener() {
            @Override
            public void onSelected(WheelItemBean type) {
                if(type != null){
                    mCompanyTypeSelectedBean = type;
                    addCompanyType(type);
                }
            }

            @Override
            public void onCancel() {
                /**/
            }
        });
        mCompanyTypePickerView.showWheelPicker();
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_add_bill){
            if(checkUploadStatus()) {
                Intent intent = new Intent(this, EnterPlatformCompanyStepTwoActivity.class);
                intent.putExtra("path", mSelectPicture);
                intent.putExtra("classid", mCompanyTypeSelectedBean.getId());
                startActivity(intent);
            }
            else{
                ToastUtils.showLongToast(this, "请上传完整的认证图片信息！");
            }
        }
        else if(v.getId() == R.id.layout_business_identify){
            mSelectType = SELECT_BUSINESS_IDENTIFY;
            mBottomDialog.showDialog(EnterPlatformCompanyStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_business_license){
            mSelectType = SELECT_BUSINESS_LICENSE;
            mBottomDialog.showDialog(EnterPlatformCompanyStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_company_identify){
            mSelectType = SELECT_COMPANY_IDENTIFY;
            mBottomDialog.showDialog(EnterPlatformCompanyStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_chemicals_identify){
            mSelectType = SELECT_CHEMICALS_IDENTIFY;
            mBottomDialog.showDialog(EnterPlatformCompanyStepOneActivity.this);
        }
        else if(v.getId() == R.id.layout_company_type){
            showCompanyTypeSelector();
        }
        else{

        }
    }

    @Override
    protected void onHttpResponse(int actionId, String response){
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_IDENTIFY_OFFSET) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mBusinessIdentifyIvLoading);
                    mBusinessIdentifyIvLoaded = true;
                    if(mSelectPicture.containsKey("businessIdentify")){
                        mSelectPicture.remove("businessIdentify");
                    }
                    mSelectPicture.put("businessIdentify", res.getJSONObject("data").getString("url"));
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_LICENSE_OFFSET) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mBusinessLicenseIvLoading);
                    mBusinessLicenseIvLoaded = true;
                    if(mSelectPicture.containsKey("businessLicense")){
                        mSelectPicture.remove("businessLicense");
                    }
                    mSelectPicture.put("businessLicense", res.getJSONObject("data").getString("url"));
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_COMPANY_IDENTIFY_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mCompanyIdentifyIvLoading);
                    mCompanyIdentifyIvLoaded = true;
                    if(mSelectPicture.containsKey("companyIdentify")){
                        mSelectPicture.remove("companyIdentify");
                    }
                    mSelectPicture.put("companyIdentify", res.getJSONObject("data").getString("url"));
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_CHEMICALS_IDENTIFY_OFFSET){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mChemicalsIdentifyIvLoading);
                    mChemicalsIdentifyIvLoaded = true;
                    if(mSelectPicture.containsKey("chemicalsIdentify")){
                        mSelectPicture.remove("chemicalsIdentify");
                    }
                    mSelectPicture.put("chemicalsIdentify", res.getJSONObject("data").getString("url"));
                }
            }
            else{
                /**/
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {

    }

    /**
     * 从相册获取图片
     */
    private void getPicFromAlbum() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
    }

    private void getPicFromCamera(){
        mTempFile = new File(Environment.getExternalStorageDirectory() +
                File.separator + "vsiji" + File.separator
                + "Pictures", System.currentTimeMillis() + ".jpg");
        if(!mTempFile.exists()){
            mTempFile.mkdirs();
        }
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this,
                    "com.example.dangerouscargodriver.fileprovider",
                    mTempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        }
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void pushFileToRemote(String file, int action){
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());
        HashMap<String, String> param = new HashMap<>();
        param.put("water", "1");

        sendHttpMultipartRequest(RemoteAPI.REQUEST_UPLOAD_FILE,
                header,
                param,
                file,
                action);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == RESULT_OK) {
                    Bitmap bitmap = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(this,
                                "com.example.dangerouscargodriver.fileprovider",
                                mTempFile);
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(mTempFile);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        bitmap = BitmapFactory.decodeStream(fis);
                        bitmap = ImageUtils.extractMiniThumb(bitmap, 232, 155);
                    }
                    else {
                        bitmap = BitmapFactory.decodeFile(mTempFile.getPath());
                    }
                    if(mSelectType == SELECT_BUSINESS_IDENTIFY) {
                        mBusinessIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_IDENTIFY_OFFSET);
                        startAnimation(mBusinessIdentifyIvLoading);
                    }
                    else if(mSelectType == SELECT_BUSINESS_LICENSE){
                        mBusinessLicenseIv.setImageBitmap(bitmap);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_LICENSE_OFFSET);
                        startAnimation(mBusinessLicenseIvLoading);
                    }
                    else if(mSelectType == SELECT_COMPANY_IDENTIFY){
                        mCompanyIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_COMPANY_IDENTIFY_OFFSET);
                        startAnimation(mCompanyIdentifyIvLoading);
                    }
                    else if(mSelectType == SELECT_CHEMICALS_IDENTIFY){
                        mChemicalsIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_CHEMICALS_IDENTIFY_OFFSET);
                        startAnimation(mChemicalsIdentifyIvLoading);
                    }
                    else{

                    }
                }
                break;
            case ALBUM_REQUEST_CODE:    //调用相册后返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    String file = ImageUtils.getRealPathFromURI(uri, this);
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    bitmap = ImageUtils.extractMiniThumb(bitmap, 320, 160);
                    if(mSelectType == SELECT_BUSINESS_IDENTIFY) {
                        mBusinessIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_IDENTIFY_OFFSET);
                        startAnimation(mBusinessIdentifyIvLoading);
                    }
                    else if(mSelectType == SELECT_BUSINESS_LICENSE){
                        mBusinessLicenseIv.setImageBitmap(bitmap);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_BUSINESS_LICENSE_OFFSET);
                        startAnimation(mBusinessLicenseIvLoading);
                    }
                    else if(mSelectType == SELECT_COMPANY_IDENTIFY){
                        mCompanyIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_COMPANY_IDENTIFY_OFFSET);
                        startAnimation(mCompanyIdentifyIvLoading);
                    }
                    else if(mSelectType == SELECT_CHEMICALS_IDENTIFY){
                        mChemicalsIdentifyIv.setImageBitmap(bitmap);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_CHEMICALS_IDENTIFY_OFFSET);
                        startAnimation(mChemicalsIdentifyIvLoading);
                    }
                    else{

                    }
                }
                break;
            default:
                break;
        }
    }

    private void startAnimation(ImageView imageView){
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);

        Animation rotateAnimation = AnimationUtils.loadAnimation(getBaseContext(),
                R.anim.anim_circle_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();
        rotateAnimation.setInterpolator(interpolator);
        imageView.startAnimation(rotateAnimation);
        imageView.setVisibility(View.VISIBLE);
    }

    private void stopAnimation(ImageView imageView){
        imageView.clearAnimation();
        imageView.setImageResource(R.drawable.ic_upload_done);
    }
}